package com.loong.rpc.proxy;

import com.loong.rpc.common.Invocation;
import com.loong.rpc.common.ServiceURL;
import com.loong.rpc.loadbalance.Loadbalance;
import com.loong.rpc.protocol.HttpClient;
import com.loong.rpc.register.RemoteRegister;

import java.lang.reflect.Proxy;
import java.util.List;

public class ProxyFactory {

    public static <T> T getProxy(Class<?> interfaceClazz) {
        // 用户配置

        Object proxyInstance = Proxy.newProxyInstance(interfaceClazz.getClassLoader(), new Class[]{interfaceClazz},
                (proxy, method, args) -> {
            Invocation invocation = new Invocation(interfaceClazz.getName(), method.getName(), method.getParameterTypes(), args);

            HttpClient httpClient = new HttpClient();

            // 服务发现
            List<ServiceURL> list = RemoteRegister.get(interfaceClazz.getName());

            // 负载均衡
            ServiceURL url = Loadbalance.random(list);

            // 服务调用
            String result = httpClient.send(url.getHostname(), url.getPort(), invocation);

            return result;
        });

        return (T) proxyInstance;
    }

}
